package edu.polsl.bio.str.node.logic;

import edu.polsl.bio.str.node.delegate.NodeManagementServiceDelegate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * //todo class description
 * <p/>
 * Created on: Jun 23, 2011 3:04:34 PM <br/>
 * <a href="http://www.polsl.pl">www.polsl.pl</a>
 *
 * @author lukasz.olczak@polsl.pl
 */
public class NodeControlBeanImpl implements NodeControlBean {
  /**
   * slf4j Logger.
   */
  private static final Logger log = LoggerFactory.getLogger(NodeControlBeanImpl.class.getName());

  private NodeContext nodeContext;

  private NodeManagementServiceDelegate nodeManagementServiceDelegate;

  @Override
  public void detachNode() throws Exception {
    log.debug("Detaching node");
    nodeManagementServiceDelegate.detachNode(nodeContext.getNodeId());
  }

  @Override
  public NodeContext getNodeContext() throws Exception {
    return nodeContext;
  }

  @Override
  public long attachNode(String managerIp, String nodeIp) throws Exception {
    if (nodeContext.isAttached()) {
      detachNode();
    }
    log.debug("Attaching node to manager {}", managerIp);
    nodeContext.setManagerIp(managerIp);
    long nodeId = nodeManagementServiceDelegate.attachNode(nodeIp, nodeContext.getNumberOfCpu());
    nodeContext.setNodeIp(nodeIp);
    nodeContext.setAttached(true);
    nodeContext.setNodeId(nodeId);
    log.info("Node attached to manager {} with id {}", nodeContext.getManagerIp(), nodeContext.getNodeId());
    return nodeId;
  }

  public void setNodeContext(NodeContext nodeContext) {
    this.nodeContext = nodeContext;
  }

  public void setManagerServiceDelegate(NodeManagementServiceDelegate nodeManagementServiceDelegate) {
    this.nodeManagementServiceDelegate = nodeManagementServiceDelegate;
  }

}
